<template>
  <div class="add-cus">
    <el-dialog v-el-drag-dialog="{ drag: true, full: true, resize: true }" :visible="true" :close-on-click-modal="false"
      @close="closeMd" title="添加客户">
      <el-form :model="fm.ps" :ref="fm.fname" :label-width="'120px'" @keyup.enter.native="onSubmit">
        <el-form-item label="客户类型" prop="cusType" :rules="[
          { required: true, message: '请选择客户类型', trigger: 'change' },
        ]">
          <el-select v-model="fm.ps.cusType" clearable filterable placeholder="新客户类型选择" style="width: 100%">
            <el-option v-for="it in allCusType" :key="it.id" :label="it.typeName" :value="it.id"
              @click.native="selCusType(it)"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="客户信息" required>
          <el-col :span="8">
            <el-form-item prop="baseUserId.realName" style="margin-bottom: 0" :rules="[
              { required: true, message: '请输入客户姓名', trigger: 'blur' },
              {
                min: 2,
                max: 10,
                message: '长度在 2 到 10 个字符',
                trigger: 'blur',
              },
            ]">
              <el-input v-model="fm.ps.baseUserId.realName" placeholder="请输入姓名"
                @blur="fillCompany(fm.ps.baseUserId.realName)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1" style="min-height: 10px">&nbsp;</el-col>
          <el-col :span="15">
            <el-form-item prop="baseUserId.phone" style="margin-bottom: 0"
              :rules="[{ validator: checkCustomPhone, trigger: 'blur' }]">
              <el-input maxlength="11" v-model="fm.ps.baseUserId.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="约定付款时间" prop="agreeOnPayDay" :rules="[
          { required: true, message: '约定付款时间不能为空' },
          { type: 'number', message: '约定付款时间为数字值' }
        ]">
          <el-input maxlength="2" style="width: 170px;" type="text" v-model.number="fm.ps.agreeOnPayDay">
            <template slot="prepend">每月</template>
            <template slot="append">号</template>
          </el-input>
        </el-form-item>

        <el-form-item label="公司名称" prop="unitName" :rules="[
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '公司名称长度最多为20位字符',
            trigger: 'blur',
          },
        ]">
          <el-input v-model="fm.ps.unitName" placeholder="请输入公司名称（最大长度为20位）"></el-input>
        </el-form-item>

        <el-form-item label="单位简称" prop="unitSimple" :rules="[
          { required: true, message: '请输入单位简称', trigger: 'blur' },
          {
            min: 1,
            max: 16,
            message: '单位简称长度最多为16位字符',
            trigger: 'blur',
          },
        ]">
          <el-input v-model="fm.ps.unitSimple" placeholder="请输入单位简称"></el-input>
        </el-form-item>

        <el-form-item label="业务员" prop="serviceMan" :rules="[
          { required: true, message: '请选择业务员', trigger: 'change' },
        ]">
          <el-select v-model="fm.ps.serviceMan" clearable filterable placeholder="请选择业务员" style="width: 100%">
            <el-option v-for="it in allSalesman" :key="it.baseUserId.uname" :label="it.baseUserId.realName"
              :value="it.baseUserId.realName + '-' + it.baseUserId.uname">
              <span>{{ it.baseUserId.realName }}</span>
              <span>{{ it.baseUserId.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职务" prop="cusRole">
          <el-input v-model="fm.ps.cusRole" placeholder="请输入职务名称"></el-input>
        </el-form-item>

        <template v-if="fm.isShowGk == 1">
          <el-form-item label="是否挂靠" prop="isDepend" :rules="[
            { required: true, message: '请选择是否挂靠', trigger: 'blur' },
          ]">
            <el-radio-group v-model="fm.ps.isDepend">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <template v-if="fm.ps.isDepend == 1">
          <el-form-item label="上网费费率" prop="onlineRatio" :rules="[
            { required: false, message: '请输入上网费费率', trigger: 'blur' },
            this.$rules.isFloat()
          ]">
            <el-input v-model.number="fm.ps.onlineRatio" placeholder="上网费费率 如：50=50%"><span
                slot="suffix">%</span></el-input>
          </el-form-item>

          <el-form-item label="开发票费率" prop="invoiceRatio" :rules="[
            { required: false, message: '请输入开发票费率', trigger: 'blur' },
            this.$rules.isFloat()
          ]">
            <el-input v-model.number="fm.ps.invoiceRatio" placeholder="开发票费率 如：50=50%"><span
                slot="suffix">%</span></el-input>
          </el-form-item>


          <el-form-item label="营业执照" prop="businessNum" :rules="[
            {
              min: 1,
              max: 36,
              message: '营业执照编号长度最多为16位字符',
              trigger: 'blur',
            },
          ]">
            <el-input v-model="fm.ps.businessNum" placeholder="请输入营业执照编号"></el-input>
          </el-form-item>

          <el-form-item label="身份证号码" prop="idCard" :rules="[{ validator: valIdCard, trigger: ['blur', 'change'] }]">
            <el-input v-model="fm.ps.idCard" placeholder="请输入身份证号码"></el-input>
          </el-form-item>

          <el-form-item label="身份证照片">
            <el-col :span="11">
              <el-form-item prop="idCardFrontImg" style="margin-bottom: 0" :rules="[
                {
                  required: false,
                  message: '请上传身份证人像面照片',
                  trigger: 'change',
                },
              ]">
                <UploadImg :imgName="'idCardFrontImg'" @getImgUrl="setImgUrl" :url="'/company/upload'"
                  :ps="{ userName: uname }" :tiptext="'（人像面）'" />
              </el-form-item>
            </el-col>
            <el-col :span="2" style="min-height: 10px">&nbsp;</el-col>
            <el-col :span="11">
              <el-form-item prop="idCardBackImg" style="margin-bottom: 0" :rules="[
                {
                  required: false,
                  message: '请上传身份证国徽面照片',
                  trigger: 'change',
                },
              ]">
                <UploadImg :imgName="'idCardBackImg'" @getImgUrl="setImgUrl" :url="'/company/upload'"
                  :ps="{ userName: uname }" :tiptext="'（国徽面）'" />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="服务内容" prop="serviceContent" :rules="[
            {
              min: 1,
              max: 200,
              message: '服务内容长度最多为200个字符串',
              trigger: 'blur',
            },
          ]">
            <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 4 }"
              placeholder="请输入服务内容，必须尽量填写清楚供应商的服务内容和产品(200字内)" maxlength="200" v-model="fm.ps.serviceContent">
            </el-input>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="onSubmit" :disabled="fm.sb.load">{{
            fm.sb.text
          }}</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import elDragDialog from "@/directive/el-drag-dialog";

import UploadImg from "@/components/UploadImg";

import * as cusService from "@/api/services/cus.service";
import * as commService from "@/api/services/common.service";

export default {
  name: "AddCus",
  directives: { elDragDialog },
  props: [],
  components: { UploadImg },
  computed: {
    ...mapGetters(["lunitNum", "uname", "name"]),
  },
  data() {
    return {
      fm: {
        fname: "addCusFm",
        sb: { load: false, text: "立即添加" },
        isShowGk: 0, // 是否显示挂靠项
        ps: {
          cusType: "",
          unitName: "",
          cusRole: "",
          agreeOnPayDay: 15,
          // 是否挂靠 默认：否
          isDepend: "0",
          // 上网费费率
          onlineRatio: '',
          // 开发票费率
          invoiceRatio: '',
          serviceMan: "",
          unitSimple: "",
          businessNum: "",
          idCard: "",
          idCardFrontImg: "",
          idCardBackImg: "",
          serviceContent: "",
          recomMan: "",
          baseUserId: {
            phone: "",
            realName: "",
          },
        },
      },
      /*-----自定义表单验证--begin----*/

      /** 验证-身份证号码 */
      valIdCard: (rule, value, callback) => {
        if (value && value !== "" && !this.FV.isIdCard(value)) {
          callback(new Error(this.FV.ERROR_ID_CARD));
        } else {
          callback();
        }
      },
      /*-----自定义表单验证--end------*/

      allCusType: [],
      allSalesman: [],
    };
  },
  created() {
    const that = this;


    that.getCompanyAllCusType();
    that.getCompanyAllSalesman();
  },
  methods: {
    /* 关闭弹框 */
    closeMd() {
      this.$emit("myClick", { state: false });
    },
    /**
     * 获取-单位所有客户类型
     */
    getCompanyAllCusType() {
      const that = this;

      commService.getCompanyAllCusType({}).then((res) => {
        if (res && res.code == 1) {
          that.allCusType = res.cusTypes;
        }
      });
    },
    /**
     * 获取-单位所有业务员(只要业务部的)
     */
    getCompanyAllSalesman() {
      const that = this;

      cusService.getCompanyAllSalesman({ deptName: "业务部", staffState: "NORMAL,TRY" }).then((res) => {
        if (res && res.code == 1) {
          that.allSalesman = res.data;

          // 设置默认值
          let index = that.allSalesman.findIndex(it => {
            return `${it.baseUserId.realName}-${it.baseUserId.uname}` == `${that.name}-${that.uname}`;
          });
          if (index != -1) that.fm.ps.serviceMan = `${that.name}-${that.uname}`;
        }
      });
    },
    /**
     * 选择-客户类型
     * @param o 客户类型对象
     */
    selCusType(o) {
      const that = this;

      that.fm.isShowGk = (o.typeName == '运输公司') ? 1 : 0;
    },
    /**
     * 设置-图片url
     * @param e 上传成功后的服务器图片url
     */
    setImgUrl(e) {
      this.fm.ps[e.name] = e.url;

      if (e.url) {
        this.clearFileValText(e.name);
      } else {
        this.$refs[this.fm.fname].validateField(e.name);
      }
    },
    /**
     * 提交表单
     */
    onSubmit() {
      const that = this;
      if (that.fm.ps.agreeOnPayDay > 28 || that.fm.ps.agreeOnPayDay < 0) {
        console.log(that.fm.ps.agreeOnPayDay)
        return alert('约定付款时间请输入1-28之间的数字')
      }

      that.$refs[that.fm.fname].validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that.fm.sb.load = true; // 添加按钮禁用效果
          let loading = that.U.qloading("提交中，请稍后..."); // 添加遮罩

          // 添加固定参数
          that.fm.ps.unitNum = that.lunitNum;
          that.fm.ps.recomMan = that.fm.ps.serviceMan;
          cusService.adupCompanyCus(that.fm.ps, "save").then((res) => {
            that.fm.sb.load = false; // 取消按钮禁用效果
            that.U.qclose(loading); // 关闭遮罩

            if (!res || res.code != 1) {
              that.U.qerror(res.msg);
            } else {
              that.U.qsuccess(res.msg);

              // 关闭弹框
              that.closeMd();

              // 调用父组件方法-重新加载数据
              let baseUserId = { uname: res.uname, ...that.fm.ps.baseUserId };

              that.$emit("reloadDg", baseUserId);
            }
          });
        }
      });
    },
    resetForm() {
      // 重置表单
      this.$refs[this.fm.fname].resetFields();
    },
    /**
     * 清除某个字段的验证信息
     * @param filed 字段名
     */
    clearFileValText(filed) {
      /*当然，你可以打印一下fields*/
      let _field = this.$refs[this.fm.fname].fields;
      _field.map((i) => {
        // 通过prop属性值相同来判断是哪个输入框，比如：要移除prop为'user'
        if (i.prop === filed) {
          // 清除验证信息
          i.clearValidate();

          return false;
        }
      });
    },
    // 验证-手机号是否存在
    checkCustomPhone(rule, value, callback) {
      let that = this;

      if (!value) {
        callback(new Error("请输入客户电话"));
      } else if (!that.FV.isPhone(value)) {
        callback(new Error("手机号为11位数字"));
      } else {
        cusService.ckCustomPhone({ phone: value }).then((res) => {
          if (res.code === 1) {
            that.fm.sb.load = false;

            callback();
          } else {
            that.fm.sb.load = true;

            callback(new Error(res.msg));
          }
        });
      }
    },
    /**
     * 输入姓名自动默认公司名称
     * @param name
     */
    fillCompany(name) {
      let that = this;

      if (that.fm.ps.baseUserId.realName) {
        that.fm.ps.unitName = that.fm.ps.baseUserId.realName + "的公司";

        that.fm.ps.unitSimple = that.fm.ps.baseUserId.realName;
      }
    },
  },
};
</script>
